package com.dpiinc.TechPage.activity

import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.SpannableString
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.*
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.lifecycle.ViewModelProviders
import androidx.paging.PagedList
import com.dpiinc.TechPage.*
import com.dpiinc.TechPage.adapter.NoteListAdapter
import com.dpiinc.TechPage.repository.Status
import com.dpiinc.TechPage.room.bean.LabelEntity
import com.dpiinc.TechPage.room.bean.NoteEntity
import com.dpiinc.TechPage.viewmodel.SearchViewModel
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.activity_search.*
import kotlinx.android.synthetic.main.select_label_layout.*
import java.util.*
import androidx.lifecycle.Observer
import com.yanzhenjie.recyclerview.widget.DefaultItemDecoration


/**
 * 搜索笔记页面   搜索界面
 * Created by X on 2018/7/22.
 */
class SearchActivity : BaseActivity() {

    private lateinit var viewModel: SearchViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search)
        viewModel = ViewModelProviders.of(this)[SearchViewModel::class.java]
        initView()
        bindView()
        initAdapter()
        showSelectLabel()
        KeyBoard(edt_search, true)
    }

    private fun initView() {
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false)
        tv_search.visibility = View.GONE
        edt_search.visibility = View.VISIBLE
        initSearch()
        list_search_result.addItemDecoration(DefaultItemDecoration(getResources().getColor(android.R.color.transparent), ViewGroup.LayoutParams.MATCH_PARENT,
                getResources().getDimensionPixelSize(R.dimen.dp_8)))
    }

    private fun bindView() {
        val labels = viewModel.loadLabels()
        labels_view.setLabels(false, labels) { _, _, label ->
            //根据data和position返回label需要显示的数据。
            label.content
        }
        labels_view.setOnLabelClickListener { _, data, _, _ ->
            val clickedLabel = data as LabelEntity
            edt_search.setText(clickedLabel.content)
            viewModel.searchByLabel(clickedLabel.id)
            hideInputMethod()
//            KeyBoard(edt_search,false)
        }
    }

    private fun initAdapter() {
        val glide = Glide.with(this)
        val adapter = NoteListAdapter(this, glide) {
            viewModel.retry()
        }.apply {
            isSearchMode = true
            hideTopDivider = true
        }
        list_search_result.adapter = adapter
        viewModel.notes.observe(this, Observer<PagedList<NoteEntity>> {
            hideLabels()
            if (it == null || it.isEmpty()) {
                empty_view.visibility = View.VISIBLE
            } else {
                empty_view.visibility = View.GONE
            }
            adapter.submitList(it)
        })
        viewModel.totalCount.observe(this, Observer {
            it ?: return@Observer
            tv_search_result_count.visibility = if (it == 0) View.GONE else View.VISIBLE
            tv_search_result_count.text = getString(R.string.label_search_result_count, it)
        })
        viewModel.refreshState.observe(this, Observer {
            it ?: return@Observer
            AWLog.e(it.toString())
            when (it.status) {
                Status.FAILED -> {
                    toast(it.msg ?: "")
                }
                else -> {
                }
            }
//            adapter.setNetworkState(it)
        })
    }

    private fun initSearch() {
        edt_search.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_GO) {
                search()
                true
            } else {
                false
            }
        }
        edt_search.setOnKeyListener { _, keyCode, event ->
            if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                search()
                true
            } else {
                false
            }
        }
        btn_clear.setOnClickListener {
            edt_search.setText("")
            showSelectLabel()
            viewModel.currentKeyword = ""
        }
        edt_search.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (s.isNullOrEmpty()) {
                    showSelectLabel()
                    empty_view.visibility = View.GONE
                    btn_clear.visibility = View.GONE
                } else {
                    btn_clear.visibility = View.VISIBLE
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

        })
    }

    private fun search() {
        edt_search.text.trim().toString().let {
            if (it.isNotEmpty()) {
                hideInputMethod()
//                KeyBoard(edt_search,false)
                viewModel.search(it)
                (list_search_result.adapter as NoteListAdapter).keyword = it
            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_search_activity, menu)
        val item = menu!!.findItem(R.id.menu_cancel)
        val spannableString = SpannableString(item.title)
        spannableString.setSpan(ForegroundColorSpan(resources.getColor(R.color.clear_note_dialog_btn_text_color_left)), 0, spannableString.length, 0)
        item.title = spannableString
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.menu_cancel -> {
//                KeyBoard(edt_search,false)
                hideInputMethod()
                finish()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    private fun showSelectLabel() {
        select_label_layout.visibility = View.VISIBLE
    }

    private fun hideLabels() {
        select_label_layout.visibility = View.INVISIBLE
    }

    private fun hideInputMethod() {
        //隐藏软键盘
//        (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
        (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
                .hideSoftInputFromWindow(edt_search.windowToken,InputMethodManager.HIDE_NOT_ALWAYS)
    }

    //强制显示或者关闭系统键盘
    fun KeyBoard(txtSearchKey: EditText, status: Boolean) {
        val timer = Timer()
        timer.schedule(object : TimerTask() {
            override fun run() {
                val m = txtSearchKey.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                if (status) {
                    m.showSoftInput(txtSearchKey, InputMethodManager.SHOW_FORCED)
                } else {
                    m.hideSoftInputFromWindow(txtSearchKey.windowToken, 0)
                }
            }
        }, 300)
    }
}
